package translate;

import java.util.ArrayList;

import temp.Temp;
import tree.BINOP;
import tree.BasicExp;
import tree.CONST;
import tree.ESEQ;
import tree.ExpList;
import tree.MEM;
import tree.MOVE;
import tree.SEQ;
import tree.TEMP;

public class RecordExp extends Ex {
	Level lev;
	static int wordSize = 4;
	ArrayList<Exp> fields = new ArrayList<Exp>();
	
	public RecordExp(Level l) {
		super(null);
		lev = l;
	}
	
	public void addField(Exp e) {
		fields.add(e);
	}

	BasicExp unEx() {
		if (fields.size() == 0) return new CONST(0);
		SEQ head, tail;
		Temp r = new Temp();
		
		head = tail = new SEQ(new MOVE(
				new TEMP(r),
				lev.frame.externalCall("malloc",new ExpList(new CONST(wordSize * fields.size()),null))
				), null
		);
		if (fields.size() == 1) return new ESEQ(new SEQ(head.left, new MOVE(
				new MEM(
						new BINOP(BINOP.PLUS, new TEMP(r), new CONST(0))
				),
				fields.get(0).unEx())
			), new TEMP(r)
		);
		for (int i = 0; i < fields.size() - 1; i++) {
			tail.right = new SEQ(new MOVE(
					new MEM(
							new BINOP(BINOP.PLUS, new TEMP(r), new CONST(i * wordSize))
					),
					fields.get(i).unEx()
				),
				null
			);
			tail = (SEQ)tail.right;
		}
		tail.right = new MOVE(
				new MEM(
						new BINOP(BINOP.PLUS, new TEMP(r), new CONST((fields.size() - 1) * wordSize))
				),
				fields.get(fields.size() - 1).unEx()
			);  
		return new ESEQ(head, new TEMP(r));
	}

	
}
